"""Secret资源提取器模块"""

from typing import Dict, Any, Optional
import base64
import logging
from src.extractors.base import Extractor

class SecretExtractor(Extractor):
    """
    Secret资源提取器
    负责从Secret资源定义中提取关键信息
    """
    
    def __init__(self, logger: Optional[logging.Logger] = None):
        """初始化Secret提取器"""
        super().__init__(logger)
        self.resource_type = "Secret"
    
    def extract(self, content: str, file_path: str = "") -> Dict[str, Any]:
        """
        从Secret YAML/JSON内容中提取信息
        
        Args:
            content: YAML/JSON格式的资源内容
            file_path: 资源文件路径，可选，用于日志记录
            
        Returns:
            提取的Secret资源信息字典
        """
        # 解析YAML/JSON内容
        resource = self.parse_content(content, file_path)
        if not resource:
            return {}
            
        # 检查是否为Secret资源
        if resource.get("kind") != "Secret":
            self.logger.warning(f"资源不是Secret: {file_path}")
            return {}
            
        # 提取基本信息
        result = self._extract_basic_info(resource)
        
        # 提取Secret特有信息
        self._extract_secret_info(resource, result)
        
        return result
    
    def _extract_basic_info(self, resource: Dict[str, Any]) -> Dict[str, Any]:
        """
        提取基本元数据信息
        
        Args:
            resource: 解析后的资源字典
            
        Returns:
            包含基本信息的字典
        """
        metadata = resource.get("metadata", {})
        
        result = {
            "kind": "Secret",
            "name": metadata.get("name", ""),
            "namespace": metadata.get("namespace", "default"),
            "creation_timestamp": metadata.get("creationTimestamp", "")
        }
        
        # 提取标签和注解
        if "labels" in metadata:
            result["labels"] = metadata.get("labels", {})
            
        if "annotations" in metadata:
            result["annotations"] = metadata.get("annotations", {})
            
        return result
    
    # 为了向后兼容，添加别名方法
    def extract_base_info(self, resource: Dict[str, Any]) -> Dict[str, Any]:
        """提取基本信息的兼容方法，调用_extract_basic_info"""
        return self._extract_basic_info(resource)
    
    def _extract_secret_info(self, resource: Dict[str, Any], result: Dict[str, Any]) -> None:
        """
        提取Secret特有信息
        
        Args:
            resource: 解析后的资源字典
            result: 要填充的结果字典
        """
        # 提取Secret类型
        secret_type = resource.get("type", "Opaque")
        result["secret_type"] = secret_type
        
        # 提取数据（不解码）
        if "data" in resource:
            # 提取数据键名
            keys = list(resource["data"].keys()) if resource["data"] else []
            result["data_keys"] = keys
            result["data_count"] = len(keys)
            
            # 安全起见，不包含实际的密钥值，只记录大小
            data_sizes = {}
            for key, value in resource["data"].items():
                if value:
                    # 估算解码后数据的大小
                    try:
                        size = len(base64.b64decode(value))
                        data_sizes[key] = f"{size} bytes"
                    except:
                        data_sizes[key] = "unknown size"
                else:
                    data_sizes[key] = "empty"
            
            result["data_sizes"] = data_sizes
            
        # 提取字符串数据（不解码）
        if "stringData" in resource:
            keys = list(resource["stringData"].keys()) if resource["stringData"] else []
            result["string_data_keys"] = keys
            result["string_data_count"] = len(keys)